package com.swx.generate.util;

import net.lingala.zip4j.ZipFile;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author Ricky
 * @date 2020-07-20
 */
public class ZipUtil {
    public static String zipFiles(File outputFile, List<File> files) throws IOException {

        if (files == null || files.size() == 0) {
            throw new RuntimeException("请输入压缩文件集合");
        }

        //压缩包文件存在则删除
        if (outputFile.exists()) {
            outputFile.delete();
        }

        if (!outputFile.getParentFile().exists()) {
            //创建当前文件父目录
            FileUtils.forceMkdirParent(outputFile);
        }

        ZipFile localFile = new ZipFile(outputFile);

        for (File file : files) {
            if (!file.exists()) {
                continue;
            }
            if (file.isFile()) {
                localFile.addFile(file);
            } else if (file.isDirectory()) {
                localFile.addFolder(file);
            }
        }

        return localFile.getFile().getCanonicalPath();
    }
}
